package com.io.IO;

import java.io.*;

/**
 * 字符流
 *
 * @author jiangbang
 * @date 2016/6/2
 */
public class CharDemo {

    public static void main(String[] args) {
        test3();
    }

    /**
     * 纯文本读取
     */
    public static void test1(){
        //创建源
        File file = new File("d:demo/1.txt");
        //选择流
        Reader reader = null;
        try {
            reader = new FileReader(file);
            //读取操作
            char[] flush = new char[10];
            int len = 0;
            while(-1!=(len=reader.read(flush))){
                String str = new String(flush,0,len);
                System.out.println(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 写出文件
     */
    public static void test2(){
        //创建源
        File file = new File("d:demo/1.txt");
        //选择流
        Writer wr = null;
        try {
            wr = new FileWriter(file,true); //添加true，表示追加
            //写出
            String msg = "锄禾日当午\r\n码农真辛苦";
            wr.write(msg);
            wr.append(msg);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                wr.flush();
                wr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 文件拷贝
     */
    public static  void test3(){
        //1.建立联系 服了对象 目的地
        File file= new File("D:/demo/1.txt");
        File file2= new File("D:/demo/2.txt");
        //2.选择流
        Writer os = null;//文件输出流  Writer FileWriter
        Reader is = null;//文件输入流  Reader FileReader
        try {
            //创建文件
            if(!file.exists()){
                file.createNewFile();
            }
            if(!file2.exists()){
                file2.createNewFile();
            }
            //拷贝操作
            is = new FileReader(file);
            os = new FileWriter(file2);

            int len = 0;
            char[] bytes = new char[100];
            while(-1!=(len=is.read(bytes))){
                os.write(bytes,0,len);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(is!=null){
                    is.close();
                }
                if(os!=null){
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
